/**
 * Created by xxcao on 2017/6/5.
 */

var sql = require('./sqlMapping');
var util = require('../util/util');
var async = require('async');
var crypto = require('../util/crypto');
var code = require('../util/code');

module.exports = {
    add:function (req, res) {
        if (util.isParameterEmpty(req.body.username, req.body.password)){
            var string = util.toJson(code.PARAMETER_IS_NULL, '参数不能为空');
            res.json(string);
            return;
        }
        mysqlPool.getConnection(function (err, connection) {
                if (err) {
                    throw err;
                }
                var pwd = crypto.getEncAse192(req.body.password,'love');
                var param = [req.body.username, pwd];

                var task1 = function (callback) {
                    connection.query(sql.user.findOne, param, function (err, result) {
                        if (result && result.length > 0){
                            res.json(util.toJson(1000, '用户已存在'));
                            connection.release();
                        } else {
                            callback(err, result);
                        }
                    });
                };
                var task2 = function (result, callback) {
                    connection.query(sql.user.insert, param, function (err, result) {
                        var jsonString = '';
                        if (result) {
                            jsonString = util.toJson(code.OPERATE_SUCCESS, '注册成功');
                        } else {
                            jsonString = util.toJson(1000, '注册失败');
                        }
                        res.json(jsonString);
                        callback(err, result);
                    });
                };
                async.waterfall([task1, task2], function (err, result) {
                    if (err) {
                        var jsonString = util.toJson(1000, '注册失败');
                        res.json(jsonString);
                    }
                    connection.release();
                });
            })
    },
    findOne:function (req, res) {
        if (util.isParameterEmpty(req.body.username, req.body.password)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        mysqlPool.getConnection(function (err, connection) {
            if (err) {
                throw err;
            }
            var pwd = crypto.getEncAse192(req.body.password,'love');
            var param = [req.body.username, pwd];
            connection.query(sql.user.findOne, param, function (err, result) {
                if (err == null && result && result.length > 0){
                    req.session.user = result[0]['user_id'];
                    res.json(util.toJson(code.OPERATE_SUCCESS, '登录成功', {userInfo:result[0]}));
                } else {
                    req.session.user = null;
                    res.json(util.toJson(1000,'用户不存在'));
                }
                connection.release();
            })
        })
    },
    clearSession:function (req, res) {
        if (util.isParameterEmpty(req.body.userid)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req,'POST')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        req.session.user = null;
        res.json(util.toJson(code.OPERATE_SUCCESS, '登出成功'));
    },
    handleWX:function (req, res) {
        if (util.isParameterEmpty(req.body.openid)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        mysqlPool.getConnection(function (err, connection) {
            if (err) {
                throw err;
            }
            new Promise(function (resolve, reject) {
               connection.query(sql.user.findOneWC, [req.body.openid], function (err, result) {
                   if (err){
                       res.json(util.toJson(1000, '操作失败'));
                       connection.release();
                   } else {
                       if(result && result.length > 0) {
                           req.session.user = result[0]['user_id'];
                           res.json(util.toJson(code.OPERATE_SUCCESS, '登录成功', {userInfo:result[0]}));
                           connection.release();
                       } else {
                           resolve(result);
                       }
                   }
               });
            }).then(function (result) {
                return new Promise(function (resolve, reject) {
                    var params = [req.body.nickname, req.body.nickname, req.body.openid, req.body.headimgurl]
                    connection.query(sql.user.insertWC, params, function (err ,result) {
                        if (err === null && result) {
                            resolve(result);
                        } else {
                            req.session.user = null;
                            res.json(util.toJson(1000, '登录失败'));
                            connection.release();
                        }
                    });
                })
            }).then(function (result) {
                return new Promise(function (resovle, reject) {
                    connection.query(sql.user.findOneWC, [req.body.openid], function (err ,result) {
                        if (err === null && result && result.length > 0) {
                            req.session.user = result[0]['user_id'];
                            res.json(util.toJson(code.OPERATE_SUCCESS, '登录成功', {userInfo:result[0]}));
                            connection.release();
                        } else {
                            req.session.user = null;
                            res.json(util.toJson(1000, '登录失败'));
                            connection.release();
                        }
                    });
                });
            });
        });
    },
    updateClientId:function (req, res) {
        if (util.isParameterEmpty(req.body.user_id, req.body.client_id)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req, 'PUT')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        mysqlPool.getConnection(function (err, connection) {
            if (err){
               throw err;  
            } 
            connection.query(sql.user.updateClientId, [req.body.client_id, req.body.user_id], function (err, result) {
               if(err){
                   res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '上传client_id失败'));
                   connection.release();
               } else {
                   res.json(util.toJson(code.OPERATE_SUCCESS, '上传client_id成功'));
                   connection.release();
               }
            });
        });
    },
    getRelated:function (req, res) {
        if (util.isParameterEmpty(req.query.user_id)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req, 'GET')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        mysqlPool.getConnection(function (err, connection) {
            if (err){
                throw err;
            }
            var sqlString = null;
            var params = [];
            if (util.isParameterEmpty(req.query.page) || isNaN(Number(req.query.page))) {
                params = [req.query.user_id, req.query.user_id];
                sqlString = sql.user.findRelatedUser;
                connection.query(sqlString, params, function (err, results) {
                    if (err){
                        res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '查询与我有关的人员失败'));
                        connection.release();
                    } else {
                        res.json(util.toJson(code.OPERATE_SUCCESS, '查询与我有关的人员成功', results));
                        connection.release();
                    }
                });
            } else {
                new Promise(function (resolve) {
                    connection.query(sql.user.findRelatedUserCount, [req.query.user_id, req.query.user_id], function (err, results) {
                        if (err){
                            res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '查询与我有关的人员失败'));
                            connection.release();
                        } else {
                            resolve(results);
                        }
                    });
                }).then(function (result) {
                    return new Promise(function (resolve) {
                        var pageSize = util.pageSize();
                        var page = Number(req.query.page);
                        page = Math.min(page, Math.ceil(Number(result[0]['count']) / pageSize));
                        page = Math.max(page, 1);
                        params = [req.query.user_id, req.query.user_id, pageSize, (page - 1) * pageSize];
                        sqlString = sql.user.findRelatedUserPage;
                        connection.query(sqlString, params, function (err, reuslts) {
                            if (err){
                                res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '查询与我有关的人员失败'));
                                connection.release();
                            } else {
                                res.json(util.toJson(code.OPERATE_SUCCESS, '查询与我有关的人员成功', reuslts));
                                connection.release();
                            }
                        })
                    })
                });
            }
        });
    }
};